/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Formularios;

import hispamail.CBackground;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author MCS
 */
public class JFrameInicio extends javax.swing.JFrame {

    private CBackground background;
    public static String libreta;
    public static String pendientes;
    public static String enviados;
    public static String recibidos;
    public static String remitente = "";
    public static String pass = "";

    /**
     * Creates new form JFrameInicio
     */
    public JFrameInicio() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPassword = new javax.swing.JPasswordField();
        jButtonConecta = new javax.swing.JButton();
        jTextConexion = new javax.swing.JTextField();
        TabCorreo = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButtonCorreo = new javax.swing.JButton();
        jComboCorreo = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Hispamail");
        setPreferredSize(new java.awt.Dimension(600, 505));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setText("Correo");

        jLabel2.setText("Password");

        jPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jPasswordKeyReleased(evt);
            }
        });

        jButtonConecta.setText("Conecta");
        jButtonConecta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConectaActionPerformed(evt);
            }
        });

        jTextConexion.setEditable(false);
        jTextConexion.setBackground(new java.awt.Color(255, 0, 0));
        jTextConexion.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextConexion.setText("Desconectado");
        jTextConexion.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextConexion.setEnabled(false);
        jTextConexion.setFocusable(false);
        jTextConexion.setRequestFocusEnabled(false);
        jTextConexion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextConexionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 525, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 359, Short.MAX_VALUE)
        );

        TabCorreo.addTab("Entradas", jPanel1);

        jPanel2.setPreferredSize(new java.awt.Dimension(600, 390));

        jButtonCorreo.setText("Nuevo correo");
        jButtonCorreo.setEnabled(false);
        jButtonCorreo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCorreoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonCorreo)
                .addContainerGap(403, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonCorreo)
                .addContainerGap(321, Short.MAX_VALUE))
        );

        TabCorreo.addTab("Envios", jPanel2);

        jComboCorreo.setEditable(true);
        jComboCorreo.setToolTipText("");
        jComboCorreo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboCorreoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(TabCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jComboCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonConecta)
                        .addGap(18, 18, 18)
                        .addComponent(jTextConexion, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 32, Short.MAX_VALUE)))
                .addGap(37, 37, 37))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonConecta)
                    .addComponent(jTextConexion, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(TabCorreo, javax.swing.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
                .addGap(33, 33, 33))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonConectaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConectaActionPerformed
        try {
            conecta();
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(JFrameInicio.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(JFrameInicio.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonConectaActionPerformed

    private void jPasswordKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordKeyReleased
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            try {
                conecta();
                System.out.println("Sin errores");
            } catch (NoSuchProviderException ex) {
                Logger.getLogger(JFrameInicio.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MessagingException ex) {
                Logger.getLogger(JFrameInicio.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jPasswordKeyReleased

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        ActCombo();
    }//GEN-LAST:event_formWindowOpened

    /*
     * Rellena el combo con los usuarios que se han logado correctamente
     */
    private void ActCombo() {
        String currentDir = System.getProperty("user.dir") + "\\mail";

        File Dir = new File(currentDir);
        if (!Dir.exists()) {
            return;
        }

        File[] lista_Archivos = Dir.listFiles();

        for (int i = 0; i < lista_Archivos.length; i++) {
            if (lista_Archivos[i].isDirectory()) {
                String proveedor = lista_Archivos[i].getName();

                File DirC = new File(currentDir + "\\" + proveedor + "\\");
                File[] listaC = DirC.listFiles();
                DefaultComboBoxModel modelo = new DefaultComboBoxModel();

                modelo.addElement("");
                for (int j = 0; j < listaC.length; j++) {
                    if (listaC[j].isDirectory()) {
                        String Correo = listaC[j].getName() + "@" + proveedor;
                        modelo.addElement(Correo);
                    }
                }
                jComboCorreo.setModel(modelo);
            }
        }
    }

    private void jButtonCorreoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCorreoActionPerformed
        background.setSuspend(true);
        JDCorreo pantalla = new JDCorreo(null, true, background);
        pantalla.setLocationRelativeTo(null);
        pantalla.setVisible(true);
    }//GEN-LAST:event_jButtonCorreoActionPerformed

    private void jTextConexionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextConexionActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextConexionActionPerformed

    private void jComboCorreoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboCorreoActionPerformed
        jPassword.requestFocus();
    }//GEN-LAST:event_jComboCorreoActionPerformed

    public void conecta() throws NoSuchProviderException, MessagingException {
        if (jTextConexion.getBackground() == Color.green) {//Estaba conectado
            //conn=desconecta(correo);
            background.parar();

            jTextConexion.setBackground(Color.red);
            jTextConexion.setText("Desconectado");
            jComboCorreo.setEnabled(true);
            ActCombo();
            jPassword.setEnabled(true);
            jButtonConecta.setText("Conecta");
            jComboCorreo.requestFocus();
            //jComboCorreo.setSelectionStart(0);
            //jComboCorreo.setSelectionEnd(jComboCorreo.getText().length());
            jButtonCorreo.setEnabled(false);

            return;
        }

        JFrameInicio.pass = new String(jPassword.getPassword());
        String correo = (String) jComboCorreo.getSelectedItem();
        boolean conn = true;

        //*********************************************************************************
        //Lo comentamos para hacer pruebas!!!!!!!!!!!!!
        /**
         * *******************************************************************************
         *
         ************************************************************************************
         */
        boolean tls = true;
        while (true) {
            try {
                conn = true;
                conn = conectacorreo(correo, pass, tls);
                break;

            } catch (MessagingException ex) {
                if (!tls) {
                    conn = false;
                    System.out.println("Error al conectarse " + ex.getMessage());
                    System.out.println("Codigo " + ex.hashCode());

                    break;
                } else {
                    tls = false;
                }
                System.out.println("Error al conectarse " + ex.getMessage());
                System.out.println("Codigo " + ex.hashCode());
            }
        }//while(true)

        String dir = System.getProperty("user.dir") + "\\mail\\";

        int pos = correo.indexOf('@', 0);
        //dir de prg\\mail\\servidor de correo\\user
        dir = dir + correo.substring(pos + 1, correo.length()) + "\\" + correo.substring(0, pos);
        System.out.println(dir);

        libreta = dir + "\\libreta.xml";
        System.out.println("libreta de direcciones=" + libreta);
        pendientes = dir + "\\pendientes\\";
        enviados = dir + "\\enviados\\";
        recibidos = dir + "\\recibidos\\";

        background = new CBackground();
        if (conn) {
            remitente = correo;

            jTextConexion.setBackground(Color.green);
            jTextConexion.setText("Conectado");
            jComboCorreo.setEnabled(false);
            jPassword.setEnabled(false);
            jButtonConecta.setText("Desconecta");
            jButtonCorreo.setEnabled(true);

            File folder = new File(enviados);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            folder = new File(recibidos);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            folder = new File(pendientes);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            background.start();

        } else {
            remitente = "";
            background.parar();

            jTextConexion.setBackground(Color.red);
            jTextConexion.setText("Desconectado");
            jComboCorreo.setEnabled(true);
            jPassword.setEnabled(true);
            jButtonConecta.setText("Conecta");
            jComboCorreo.requestFocus();
            //jComboCorreo.setSelectionStart(0);
            //jComboCorreo.setSelectionEnd(jComboCorreo.getText().length());
            jButtonCorreo.setEnabled(false);
        }
    }
    /*
     * Solo sirve para comprobar las credenciales y la conectividad
     * al final hacemos un close
     * ese close hace que no tengamos que llamar a desconexión
     * y no dejemos nada abierto un tiempo innecesario
     */

    public boolean conectacorreo(String correo, String pass, boolean tls) throws NoSuchProviderException, MessagingException {
        Properties datos = new Properties();

        int pos = correo.indexOf('@', 0);

        if (pos < 1 || pos >= correo.length() - 1) {
            JOptionPane.showMessageDialog(null, "La dirección de correo está mal formada");
            return false;
        }

        String user = correo.substring(0, pos);

        //!!!!!!!!!!!!!!!!!!!! Lo he puesto para cortar la ejecución ****************************
        //if (true) return true;
        String smtp = "smtp." + correo.substring(pos + 1, correo.length());

        datos.setProperty("mail.smtp.host", smtp);

        if (tls) {
            datos.setProperty("mail.smtp.starttls.enable", "true"); //si usa TLS o no
        } else {
            datos.setProperty("mail.smtp.starttls.enable", "false"); //si usa TLS o no
        }
        datos.setProperty("mail.smtp.port", "587");//465 o 587 o 25
        datos.setProperty("mail.smtp.user", user);
        datos.setProperty("mail.smtp.auth", "true");
        datos.setProperty("mail.smtps.auth ", "true");
        datos.put("mail.debug", "true");  //para que nos muestre en detalle el proceso
        datos.put("mail.smtp.socketFactory.port", "587");//465 ssl, 587 tls o 25
        datos.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        datos.put("mail.smtp.ssl.trust", smtp);

        datos.setProperty("mail.smtp.timeout", "15000");
        datos.setProperty("mail.smtp.connectiontimeout", "15000");
        datos.setProperty("mail.imap.timeout", "15000");
        datos.setProperty("mail.imap.connectionpooltimeout", "15000");

        Session sesion = Session.getDefaultInstance(datos);

        Transport t = sesion.getTransport("smtp");
        //
        boolean ret = true;
        try {
            t.connect(smtp, user, pass);
        }/* catch (MessagingException ex) {
         System.out.println(ex.toString());
         ret = false;
         } */ finally {
            t.close();
        }

        return ret;
    }

    //No va a hacer falta usarla porque tengo que hacer un close después de la conexión
    //o de los envíos
    /*
     public boolean desconecta(String correo) throws NoSuchProviderException, MessagingException{
     Properties datos= new Properties();
        
     int pos=correo.indexOf("@", 0);
     String user=correo.substring(0, pos);
        
     String smtp="smtp."+correo.substring(pos+1, correo.length());
        
     datos.setProperty("mail.smtp.host", smtp);
     datos.setProperty("mail.smtp.starttls.enable", "true"); //si usa TLS o no
     datos.setProperty("mail.smtp.port", "587");//465 o 587 o 25
     datos.setProperty("mail.smtp.user", user);
     datos.setProperty("mail.smtp.auth", "true");
     datos.setProperty("mail.smtps.auth ", "true");
     datos.put("mail.debug", "true");  //para que nos muestre en detalle el proceso
     datos.put("mail.smtp.socketFactory.port", "587");//465 ssl, 587 tls o 25
     datos.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        
     datos.setProperty("mail.smtp.timeout", "15000");
     datos.setProperty("mail.smtp.connectiontimeout", "15000");
     datos.setProperty("mail.imap.timeout", "15000");
     datos.setProperty("mail.imap.connectionpooltimeout", "15000");
        
     Session sesion = Session.getDefaultInstance(datos);
        
     Transport t = sesion.getTransport("smtp");
     t.close();
        
     return true;
     }
     */
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws AddressException, MessagingException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameInicio().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTabbedPane TabCorreo;
    private javax.swing.JButton jButtonConecta;
    private javax.swing.JButton jButtonCorreo;
    private javax.swing.JComboBox jComboCorreo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPasswordField jPassword;
    private javax.swing.JTextField jTextConexion;
    // End of variables declaration//GEN-END:variables
}
